package com.shuorikeji.huohuo.utils;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextPaint;
import android.util.Log;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.bean.BookDetailInfoSubBean;
import com.shuorikeji.huohuo.bean.NetImgMainBean;
import com.shuorikeji.huohuo.bean.ReadBookConfigBean;
import com.shuorikeji.huohuo.bean.UserInfoBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.http.RetrofitUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wxl on 2022/1/14 14:48
 * 业务相关工具类
 */
public class BusinessUtils {

    public static ReadBookConfigBean getReadBookConfig() {
        ReadBookConfigBean data = null;
        String info = (String) PreUtils.get(Constant.READ_BOOK_CONFIG, "");
        data = GsonUtil.parseJsonToBean(info, ReadBookConfigBean.class);
        return data;
    }

    /**
     * 提供精确的除法运算。当发生除不尽的情况时，由scale参数指定精度，以后的数字四舍五入
     *
     * @param v1    被除数
     * @param v2    除数
     * @param scale 表示需要精确到小数点以后几位
     * @param isUp  是否是四舍五入，否则，去掉
     * @return 两个参数的商
     */
    public static BigDecimal divBigDecimal(BigDecimal v1, BigDecimal v2, int scale, boolean isUp) {
        BigDecimal newBig = null;
        try {
            if (scale < 0) {
                scale = 0;
            }
            if (isUp) {
                newBig = v1.divide(v2, scale, BigDecimal.ROUND_HALF_UP);
            } else {
                newBig = v1.divide(v2, scale, BigDecimal.ROUND_DOWN);
            }
        } catch (Exception e) {
            newBig = new BigDecimal("0.00");
        }
        return newBig;
    }

    /**
     * 提供精确的乘法运算
     *
     * @param v1    被乘数
     * @param v2    乘数
     * @param scale 保留scale 位小数
     * @return 两个参数的积
     */
    public static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale) {
        BigDecimal newBig = null;
        try {
            if (scale < 0) {
                scale = 0;
            }
            newBig = v1.multiply(v2).setScale(scale, BigDecimal.ROUND_HALF_UP);
        } catch (Exception e) {
            e.printStackTrace();
            newBig = new BigDecimal("0.00");
        }
        return newBig;
    }

    /**
     * 清除webView，防止OOM
     *
     * @param webView 要清除的webView
     */
    public static void clearWebView(WebView webView) {
        try {
            if (webView != null) {
                ViewParent parent = webView.getParent();
                if (parent != null) {
                    ((ViewGroup) parent).removeView(webView);
                }
                webView.removeAllViews();
                webView.destroy();
                webView = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BookDetailInfoSubBean getCurReadingBookInfo() {
        BookDetailInfoSubBean data = null;
        String info = (String) PreUtils.get(Constant.CUR_READING_BOOK_ZJ, "");
        data = GsonUtil.parseJsonToBean(info, BookDetailInfoSubBean.class);
        return data;
    }

    /**
     * 书籍标签
     *
     * @return str
     */
    public static String getNewBookYxTag(List<String> tags) {
        String str = "";
        try {
            if (tags != null && tags.size() > 0) {
                for (int i = 0; i < tags.size(); i++) {
                    str = str + "," + tags.get(i);
                }
                str = str.substring(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 设置textView的粗体显示效果
     *
     * @param textView   对应的view
     * @param isShowFold 是否设置粗体
     */
    public static void setTxtFold(TextView textView, boolean isShowFold) {
        TextPaint textPaint = textView.getPaint();
        textPaint.setFakeBoldText(isShowFold);
        textView.postInvalidate();
    }

    public static void clearDialog(Dialog dialog) {
        if (dialog != null) {
            WeakReference<Dialog> weakReference = new WeakReference<>(dialog);
            dialog.dismiss();
            dialog = null;
        }
    }

    /**
     * 加载图片
     *
     * @param context   上下文
     * @param imgPath   图片path
     * @param imageView view
     */
    public static void setLoadImg(Context context, Object imgPath, ImageView imageView) {
        Glide.with(context)
                .load(imgPath)
                .placeholder(R.mipmap.icon_app_logo)
                .error(R.mipmap.icon_app_logo)
                .format(DecodeFormat.PREFER_ARGB_8888)
                .into(imageView);
    }

    /**
     * 加载图片
     *
     * @param context   上下文
     * @param imgPath   图片path
     * @param imageView view
     */
    public static void setLoadImg(Context context, Object imgPath, int res, ImageView imageView) {
        Glide.with(context)
                .load(imgPath)
                .placeholder(res)
                .error(res)
                .format(DecodeFormat.PREFER_ARGB_8888)
                .into(imageView);
    }

    public static void setLoadImgForLayout(Context context, String imgPath, LinearLayout layout) {
        Glide.with(context)
                .load(imgPath)
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        layout.setBackground(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });

    }

    /**
     * 根据cycle获取string内容
     *
     * @param cycle 1上周；2本月；3上月；4本年；5上年； 6本周
     * @return string
     */
    public static String getDateCycle(int cycle) {
        String dateInfo = "本月数据";
        switch (cycle) {
            case 1:
                dateInfo = "上周数据";
                break;
            case 2:
                dateInfo = "本月数据";
                break;
            case 3:
                dateInfo = "上月数据";
                break;
            case 4:
                dateInfo = "本年数据";
                break;
            case 5:
                dateInfo = "上年数据";
                break;
            case 6:
                dateInfo = "本周数据";
                break;
            default:
                dateInfo = "本月数据";
                break;
        }
        return dateInfo;
    }

    /**
     * 获取上月周期范围
     *
     * @param currentMonth 当前月份
     * @param currentDay   当前日期
     * @return string
     */
    public static String getLastMonthDateLimit(int currentMonth, int currentDay) {
        String dateLimit = "";
        if (currentMonth == 1) {
            if (currentDay >= 15) {
                dateLimit = "(12/15-1/14)";
            } else {
                dateLimit = "(11/15-12/14)";
            }
        } else if (currentMonth == 2) {
            if (currentDay >= 15) {
                dateLimit = "(1/15-2/14)";
            } else {
                dateLimit = "(12/15-1/14)";
            }
        } else {
            if (currentDay >= 15) {
                dateLimit = "(" + (currentMonth - 1) + "/15-" + currentMonth + "/14)";
            } else {
                dateLimit = "(" + (currentMonth - 2) + "/15-" + (currentMonth - 1) + "/14)";
            }
        }
        return dateLimit;
    }

    /**
     * 获取本月周期范围
     *
     * @param currentMonth 当前月份
     * @param currentDay   当前日期
     * @return string
     */
    public static String getThisMonthDateLimit(int currentMonth, int currentDay) {
        String dateLimit = "";
        if (currentMonth == 12) {
            if (currentDay >= 15) {
                dateLimit = "(" + currentMonth + "/15-1/14)";
            } else {
                dateLimit = "(11/15-12/14)";
            }
        } else if (currentMonth == 1) {
            if (currentDay >= 15) {
                dateLimit = "(1/15-2/14)";
            } else {
                dateLimit = "(12/15-1/14)";
            }
        } else {
            if (currentDay >= 15) {
                dateLimit = "(" + currentMonth + "/15-" + (currentMonth + 1) + "/14)";
            } else {
                dateLimit = "(" + (currentMonth - 1) + "/15-" + currentMonth + "/14)";
            }
        }
        return dateLimit;
    }

    /**
     * 跳转到系统设置
     *
     * @param context 上下文
     */
    public static void goToSetting(Context context) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else {
            // 其他
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 跳转到系统设置
     *
     * @param context 上下文
     */
    public static void goToSettingPage(Context context) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    /**
     * 检查是否有某一权限
     *
     * @param context    上下文
     * @param permission 某一权限
     * @return 布尔值
     */
    public static boolean checkPermissions(Context context, String permission) {
        boolean isPermissions = false;//是否已申请了该权限，true已有该权限；false没有该权限
        int checkPermission = ContextCompat.checkSelfPermission(context, permission);
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                isPermissions = false;
            } else {
                isPermissions = true;
            }
        } else {
            isPermissions = false;
        }
        return isPermissions;
    }

    /**
     * 检查是否已开启消息通知
     *
     * @param context 上下文
     * @return 是否开启了消息通知，true开启，false不开启
     */
    public static boolean isOpenMsgNotice(Context context) {
        boolean isOpenMsgNotice = false;//是否开启了消息通知，true开启，false不开启
        try {
            isOpenMsgNotice = NotificationManagerCompat.from(context).areNotificationsEnabled();
        } catch (Exception e) {
            e.printStackTrace();
            isOpenMsgNotice = false;
        }
        return isOpenMsgNotice;
    }

    /**
     * 获取assets中的数据
     *
     * @param context 上下文
     * @return str
     */
    public static String getAssetsJson(Context context) {
        String jsonStr = "";
        try {
            AssetManager assetManager = context.getAssets(); // 获得assets资源管理器(assets中的文件无法直接访问，可以使用AssetManager访问)
            InputStreamReader inputStreamReader = new InputStreamReader(assetManager.open("city.json"), "UTF-8"); // 使用IO流读取json文件内容
            BufferedReader br = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            inputStreamReader.close();
            jsonStr = builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            jsonStr = "";
        }
        return jsonStr;
    }

    /**
     * 获取版本名称
     *
     * @param context 上下文
     * @return str
     */
    public static String getVersionName(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 字符串判断空
     *
     * @param cs cs
     * @return bool
     */
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * 获取设备宽度（px）
     *
     * @param context 上下文
     * @return int
     */
    public static int getDeviceWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取设备高度（px）
     *
     * @param context 上下文
     * @return int
     */
    public static int getDeviceHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    public static UserInfoBean getUserInfo() {
        UserInfoBean data = null;
        try {
            String info = (String) PreUtils.get(Constant.LOGIN_USER_INFO, "");
            data = GsonUtil.parseJsonToBean(info, UserInfoBean.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static String getMhTag(List<String> tags) {
        String str = "";
        try {
            if (tags != null && tags.size() > 0) {
                for (int i = 0; i < tags.size(); i++) {
                    str = str + "," + tags.get(i);
                }
                str = str.substring(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static float getCurrentScreenLight(Context context) {
        float screenBrightness = 0;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            int mode = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE);
            if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                // 如果模式是自动，获取自动亮度值
                screenBrightness = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS);
            } else {
                // 如果模式是手动，获取手动亮度值
                screenBrightness = Settings.System.getInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS);
            }
            // 将亮度值转换为百分比（假设最大值为255）
            float percentage = (screenBrightness / 255.0f) * 100;
            return percentage;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return screenBrightness;
    }

    /**
     * 书籍标签
     *
     * @return str
     */
    public static String getAllIds(String idsStr) {
        String str = "";
        try {
            str = idsStr.substring(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String longTimeToDateStr(long time, String format) {
        String timeStr = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format); // 设置日期格式
        timeStr = sdf.format(new Date(time)); // 将时间戳转换为日期字符串
        return timeStr;
    }

    /**
     * 上传多张图片
     *
     * @param list     图片
     * @param callBack 回调
     */
    public static void upLoadPhotos(List<String> list, ClickCallBack callBack) {
        List<String> newList = new ArrayList<>();
        List<String> oldList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = list.size() - 1; i >= 0; i--) {
                if (BusinessUtils.isEmpty(list.get(i))) {
                    list.remove(i);
                }
            }
            oldList.addAll(list);
            for (int i = oldList.size() - 1; i >= 0; i--) {
                if (oldList.get(i).startsWith("http")) {
                    newList.add(oldList.get(i));
                    oldList.remove(i);
                }
            }
            if (oldList != null && oldList.size() > 0) {
                for (int i = 0; i < oldList.size(); i++) {
                    uploadPhoto(oldList.get(i), i, new ClickCallBack() {
                        @Override
                        public void onClick(int flag, Object obj) {
                            switch (flag) {
                                case 1:
                                    //上传成功
                                    NetImgMainBean data = (NetImgMainBean) obj;
                                    newList.add(data.getData().getFullurl());
                                    if (newList.size() == list.size()) {
                                        if (callBack != null) {
                                            callBack.onClick(1, newList);
                                        }
                                    }
                                    break;
                                case 2:
                                    //上传失败
                                    if (callBack != null) {
                                        callBack.onClick(2, "Upload failure");
                                    }
                                    break;
                                case 3:
                                    //一张图片正在上传
                                    callBack.onClick(3, null);
                                    break;
                            }
                        }
                    });
                }
            } else {
                if (newList != null && newList.size() > 0) {
                    if (callBack != null) {
                        callBack.onClick(1, newList);
                    }
                } else {
                    if (callBack != null) {
                        callBack.onClick(2, "上传失败");
                    }
                }
            }
        }
    }

    /**
     * 上传单张图片(php)
     *
     * @param callBack 回调
     */
    public static void uploadPhoto(String path, int index, ClickCallBack callBack) {
        File file = new File(path);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        RequestBody requestBody = builder.build();

        Call<NetImgMainBean> uploadPhoto = RetrofitUtils.getService().uploadPhoto(requestBody);
        uploadPhoto.enqueue(new Callback<NetImgMainBean>() {
            @Override
            public void onResponse(Call<NetImgMainBean> call, Response<NetImgMainBean> response) {
                Log.i("wxl", "上传图片返回的数据：" + response.code());
                if (response.code() == 200) {
                    if (callBack != null) {
                        callBack.onClick(1, response.body());
                    }
                } else {
                    Log.e("wxl", "上传失败：" + response.message());
                    if (callBack != null) {
                        callBack.onClick(2, null);
                    }
                }
            }

            @Override
            public void onFailure(Call<NetImgMainBean> call, Throwable t) {
                Log.e("wxl", "上传失败：" + t.getMessage());
                if (callBack != null) {
                    callBack.onClick(2, null);
                }
            }
        });
    }

    public static Bitmap getQRCode(String content, int width, int height) {
        QRCodeWriter writer = new QRCodeWriter();
        try {
            // 设置容错率
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            // 设置字符集
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            // 生成二维码的位矩阵
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            // 将位矩阵转换为像素数组
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    pixels[y * width + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE;
                }
            }

            // 创建Bitmap并设置像素
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 清除缓存
     *
     * @param context 上下文
     */
    public static void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(context.getExternalCacheDir());
        }
    }

    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    /**
     * 获取缓存大小
     *
     * @param context
     * @return
     * @throws Exception
     */
    public static String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     *
     * @param size size
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "B";
        }
        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }
        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }
        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    public static void openAppSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
        context.startActivity(intent);
    }

    public static long longTimeSjc(long time1, long time2) {
        long sjc = 0;
        try {
            sjc = (time1 - time2) / 1000;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sjc;
    }
}
